package com.example.exam.interceptor;

import com.example.exam.logInfo.service.LogInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class TestInterceptor implements HandlerInterceptor {
    @Autowired
    LogInfoService ls;
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }
    @Override
        /**
            * @Description:后置拦截，当username为空跳转至首页
            * @Param: [request, response, handler]
            * @return: boolean
            * @Author: xhw
            * @Date: 2021/7/26
            */
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String url=request.getServletPath();
        HttpSession session=request.getSession();
        String username=(String)session.getAttribute("username");
        Object id=session.getAttribute("id");
        if(username==null){
            //System.out.println("调用");
            response.sendRedirect("/user/toLogin");
           //request.getRequestDispatcher("/LogInfoController/toLogin").forward(request,response);
            return false;
        }else{
            /*LogInfoBean lib=new LogInfoBean();
            lib.setUser_id(Integer.parseInt(id.toString()));
            lib.setOp_time(new Date());
            lib.setUrl(url);
            if(ls==null){
                BeanFactory factory=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
                ls=(LogInfoService) factory.getBean("logInfoService");
            }

            int i=ls.insertLog(lib);
            if(i>0){
                System.out.println("日志更新成功");
            }*/
            //System.out.println("没调用");
            return true;
        }

    }
}
